package com.mbf.crm.interceptor;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.mbf.crm.common.Constants;
import com.mbf.crm.common.ImUser;
import com.mbf.crm.model.domain.Member;

/**
 * 用于WebSocket记录用户信息
 * @author Administrator
 *
 */
public class WebSocketHandlerInterceptor extends
		HttpSessionHandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler socketHandler,
			Map<String, Object> map) throws Exception {
		if(request instanceof ServletServerHttpRequest){
			ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
			HttpSession session = serverHttpRequest.getServletRequest().getSession();
			if(session != null){
				Member member = (Member) session.getAttribute(Constants.SESSION_MEMBER_KEY);
				map.put(Constants.WEB_SOCKET_USERNAME, new ImUser(member.getId(), member.getRealName()));
			}
		}
		return super.beforeHandshake(request, response, socketHandler, map);
	}
	
}
